package com.example.fangyimanagement.core;

import java.lang.reflect.Field;

/**
 * 业务异常类
 * @author : xiect
 * @author clu
 * @version 2.0 增加业务异常，允许将额外的异常信息加入到异常中，但是返回给前端的时候，仅仅保留摘要信息
 * @date 2021年07月19日 14:17
 **/
public class BizException extends RuntimeException {

    private static final Field MESSAGE_FIELD;

    static {
        try {
            MESSAGE_FIELD = Throwable.class.getDeclaredField("detailMessage");
            MESSAGE_FIELD.setAccessible(true);
        }
        catch (NoSuchFieldException e) {
            throw new BizException("初始化失败", e);
        }
    }

    private final String bizMessage;

    /**
     * 更加细化的错误信息，不会返回到前端，但是会输出在日志中
     */
    private String detail;

    public BizException(String message) {
        super(message);
        this.bizMessage = this.getMessage();
    }

    public BizException(String message, Throwable cause) {
        super(message, cause);
        this.bizMessage = this.getMessage();
    }

    public BizException(Throwable cause) {
        super(cause);
        this.bizMessage = this.getMessage();
    }

    public BizException(String message, Object... params) {
        this(StringUtils.format(message, params));
    }

    public BizException(Throwable cause, String message, Object... params) {
        super(StringUtils.format(message, params), cause);
        this.bizMessage = this.getMessage();
    }

    /**
     * 获取业务错误，仅仅是错误的概要信息
     * @return
     */
    public String getBizMessage() {
        return bizMessage;
    }

    private void fixMessage() {
        try {
            MESSAGE_FIELD.set(this, this.bizMessage + "：" + this.detail);
        }
        catch (IllegalAccessException e) {
            throw new BizException("细化异常信息失败");
        }
    }

    public String getDetail() {
        return detail;
    }

    public BizException setDetail(String detail, Object... params) {
        this.detail = StringUtils.format(detail, params);
        if (this.detail != null) {
            // 修改明细的时候，将message替换成明细信息，便于打印异常栈的时候输出到日志中
            this.fixMessage();
        }
        return this;
    }

//    public BizException setDetailInfo(MyJson detailInfo) {
//        return this.setDetail(detailInfo.toJSONString());
//    }

    @Override
    public String getMessage() {
        return super.getMessage();
    }
}
